package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.GroupJoinRequestMessage;
import host.skiree.nettydemo.message.GroupJoinResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.impl.RoomChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.Set;

/**
 * @author gcl
 * @date 2022/9/21 9:11
 */
public class GroupJoin implements MessageHandler {
    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        GroupJoinRequestMessage groupJoinRequestMessage = (GroupJoinRequestMessage) message;
        String groupName = groupJoinRequestMessage.getGroupName();
        if (RoomChannelImpl.ROOM_CHANNEL_MAP.get(groupName) == null){
            ctx.writeAndFlush(new GroupJoinResponseMessage(false, "该聊天室不存在"));
        }else {
            String userName = groupJoinRequestMessage.getUsername();
            Set<String> users = RoomChannelImpl.ROOM_CHANNEL_MAP.get(groupName);
            if ( users.contains(userName) ){
                ctx.writeAndFlush(new GroupJoinResponseMessage(false, "您已在该聊天室"));
            }else {
                users.add(userName);
                RoomChannelImpl.ROOM_CHANNEL_MAP.put(groupName, users);
                ctx.writeAndFlush(new GroupJoinResponseMessage(true, "您已成功进入聊天室 " + groupName));
            }
        }
    }
}
